<template>
  <div class="condition-config-panel">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="base" title="基本信息">
        <BaseNodeInfoPanel
          :label="local.label"
          :description="local.description"
          @update:label="(v) => (local.label = v)"
          @update:description="(v) => (local.description = v)"
        />
      </a-tab-pane>
      <a-tab-pane key="branches" title="条件属性">
        <div class="branches-container">
          <div class="branches-header">
            <h4>分支配置</h4>
            <a-button size="small" @click="addBranch">
              <template #icon>
                <icon-plus />
              </template>
              添加分支
            </a-button>
          </div>

          <div class="branches-list">
            <div
              v-for="(branch, branchIdx) in local.branches"
              :key="branchIdx"
              class="branch-container"
            >
              <div class="branch-header">
                <div class="branch-title">
                  <a-input
                    v-model="branch.name"
                    size="small"
                    placeholder="分支名称"
                    style="width: 120px; margin-left: 8px"
                  />
                </div>
                <div class="branch-actions">
                  <a-button
                    size="mini"
                    type="text"
                    status="danger"
                    @click="removeBranch(branchIdx)"
                  >
                    <template #icon>
                      <icon-delete />
                    </template>
                  </a-button>
                </div>
              </div>

              <div class="branch-content">
                <div class="condition-builder">
                  <!-- 模式选择 -->
                  <div class="mode-selector">
                    <a-radio-group v-model="branch.conditionMode" type="button">
                      <a-radio value="rules">条件规则</a-radio>
                      <a-radio value="formula">公式</a-radio>
                    </a-radio-group>
                  </div>

                  <!-- 条件规则构建器 -->
                  <div
                    v-if="branch.conditionMode === 'rules'"
                    class="rules-builder"
                  >
                    <div class="rules-header">
                      <a-select
                        v-model="branch.logicalOperator"
                        size="small"
                        style="width: 70px"
                      >
                        <a-option value="and">且</a-option>
                        <a-option value="or">或</a-option>
                      </a-select>
                      <span class="rules-title">条件规则</span>
                    </div>

                    <div class="rules-list">
                      <div
                        v-for="(rule, ruleIdx) in branch.conditionRules"
                        :key="ruleIdx"
                        class="rule-item"
                      >
                        <a-select
                          v-model="rule.field"
                          size="small"
                          style="flex: 1"
                        >
                          <a-option value="leaveDays">请假天数</a-option>
                          <a-option value="department">发起部门</a-option>
                          <a-option value="amount">金额</a-option>
                          <a-option value="status">状态</a-option>
                        </a-select>

                        <a-select
                          v-model="rule.operator"
                          size="small"
                          style="flex: 1"
                        >
                          <a-option value="equals">等于</a-option>
                          <a-option value="notEquals">不等于</a-option>
                          <a-option value="greaterThan">大于</a-option>
                          <a-option value="greaterThanOrEqual"
                            >大于等于</a-option
                          >
                          <a-option value="lessThan">小于</a-option>
                          <a-option value="lessThanOrEqual">小于等于</a-option>
                          <a-option value="contains">包含</a-option>
                          <a-option value="belongsTo">属于</a-option>
                        </a-select>

                        <a-input
                          v-if="rule.operator !== 'belongsTo'"
                          v-model="rule.value"
                          size="small"
                          placeholder="请输入值"
                          style="flex: 1"
                        />
                        <a-button
                          v-else
                          size="small"
                          @click="selectValue(rule)"
                          style="flex: 1; justify-content: flex-start"
                        >
                          <template #icon>
                            <icon-user />
                          </template>
                          已选择({{ rule.selectedCount || 0 }})
                        </a-button>

                        <div class="rule-actions">
                          <a-button
                            size="mini"
                            type="text"
                            status="danger"
                            @click="removeRule(branchIdx, ruleIdx)"
                          >
                            <template #icon>
                              <icon-delete />
                            </template>
                          </a-button>
                          <a-button
                            size="mini"
                            type="text"
                            status="success"
                            @click="addRule(branchIdx)"
                          >
                            <template #icon>
                              <icon-plus />
                            </template>
                          </a-button>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 公式模式 -->
                  <div v-else class="formula-editor">
                    <div class="formula-container">
                      <label class="formula-label">条件公式</label>
                      <a-textarea
                        v-model="branch.formulaText"
                        class="formula-input"
                        placeholder="请输入条件公式，例如：name=100&&age>20"
                        :rows="6"
                        :auto-size="{ minRows: 4, maxRows: 8 }"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="outputs" title="自定义出参">
        <BaseOutputsPanel v-model="local.outputs" />
      </a-tab-pane>
    </a-tabs>
    <div class="panel-actions">
      <a-button type="primary" size="small" @click="save">保存</a-button>
      <a-button size="small" @click="$emit('close')">关闭</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { Message } from "@arco-design/web-vue";
import { IconUser, IconDelete, IconPlus } from "@arco-design/web-vue/es/icon";
import BaseNodeInfoPanel from "./base/BaseNodeInfoPanel.vue";
import BaseOutputsPanel from "./base/BaseOutputsPanel.vue";

const props = defineProps<{ node: any }>();
const emit = defineEmits(["update", "close"]);

const activeTab = ref("base");

// 初始化分支数据，每个分支都有自己的条件配置
const initializeBranch = (branchData: any = {}) => {
  // 处理保存的数据结构
  let conditionMode = "rules";
  let logicalOperator = "or";
  let formulaText = "";
  let conditionRules = [
    {
      field: "leaveDays",
      operator: "greaterThanOrEqual",
      value: "7",
      selectedCount: 0,
    },
  ];

  // 如果有保存的条件数据，从中提取配置
  if (branchData.conditionData) {
    conditionMode = branchData.conditionData.mode || "rules";
    if (branchData.conditionData.mode === "rules") {
      logicalOperator = branchData.conditionData.logicalOperator || "or";
      conditionRules = branchData.conditionData.rules || conditionRules;
    } else if (branchData.conditionData.mode === "formula") {
      formulaText = branchData.conditionData.formula || "";
    }
  } else {
    // 兼容旧格式
    conditionMode = branchData.conditionMode || "rules";
    logicalOperator = branchData.logicalOperator || "or";
    formulaText = branchData.formulaText || "";
    conditionRules = branchData.conditionRules || conditionRules;
  }

  return {
    name: branchData.name || "",
    condition: branchData.condition || "",
    conditionMode,
    logicalOperator,
    formulaText,
    conditionRules,
  };
};

const local = reactive({
  label: props.node.data.label || "",
  description: props.node.data.description || "",
  branches: props.node.data.branches
    ? props.node.data.branches.map((branch: any) => initializeBranch(branch))
    : [
        initializeBranch({ name: "分支A" }),
        initializeBranch({ name: "分支B" }),
      ],
  outputs: props.node.data.outputs
    ? JSON.parse(JSON.stringify(props.node.data.outputs))
    : [],
});

function addRule(branchIdx: number) {
  local.branches[branchIdx].conditionRules.push({
    field: "leaveDays",
    operator: "equals",
    value: "",
    selectedCount: 0,
  });
}

function removeRule(branchIdx: number, ruleIdx: number) {
  local.branches[branchIdx].conditionRules.splice(ruleIdx, 1);
}

function selectValue(rule: any) {
  // 这里可以打开选择器弹窗
  console.log("选择值", rule);
  rule.selectedCount = (rule.selectedCount || 0) + 1;
}

function addBranch() {
  const branchNames = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
  const nextIndex = local.branches.length;
  const nextName = branchNames[nextIndex] || `分支${nextIndex + 1}`;
  local.branches.push(initializeBranch({ name: `分支${nextName}` }));
}

function removeBranch(idx: number) {
  if (local.branches.length <= 2) {
    Message.warning("条件分支不能少于2个");
    activeTab.value = "branches";
    return;
  }
  local.branches.splice(idx, 1);
}

function save() {
  // 组装各标签的校验器：优先当前激活标签
  const validators: Record<string, () => boolean> = {
    base: () => true,
    branches: () => {
      if (!local.branches || local.branches.length < 2) {
        Message.error("请至少保留 2 个条件分支");
        activeTab.value = "branches";
        return false;
      }
      return true;
    },
    outputs: () => {
      const list = Array.isArray(local.outputs) ? local.outputs : [];
      for (let i = 0; i < list.length; i++) {
        const it: any = list[i] || {};
        const name = String(it.name ?? "").trim();
        const key = String(it.key ?? "").trim();
        if (!name || !key) {
          Message.error("自定义出参的名称和Key为必填项");
          activeTab.value = "outputs";
          return false;
        }
      }
      return true;
    },
  };

  const order = [activeTab.value, "branches", "outputs", "base"]
    .filter((v, idx, arr) => !!validators[v] && arr.indexOf(v) === idx);
  for (const key of order) {
    const ok = validators[key]();
    if (!ok) return;
  }
  // 处理每个分支的条件数据
  const processedBranches = local.branches.map((branch) => {
    const processedBranch: any = {
      name: branch.name,
      condition: branch.condition,
    };

    // 根据模式保存不同的条件数据
    if (branch.conditionMode === "rules") {
      processedBranch.conditionData = {
        mode: "rules",
        logicalOperator: branch.logicalOperator,
        rules: branch.conditionRules,
      };
    } else {
      processedBranch.conditionData = {
        mode: "formula",
        formula: branch.formulaText,
      };
    }

    return processedBranch;
  });

  emit("update", props.node.id, {
    label: local.label,
    description: local.description,
    branches: processedBranches,
    outputs: local.outputs,
  });
  emit("close");
}

watch(
  () => props.node,
  (n) => {
    local.label = n.data.label || "";
    local.description = n.data.description || "";
    local.branches = n.data.branches
      ? n.data.branches.map((branch: any) => initializeBranch(branch))
      : [
          initializeBranch({ name: "分支A" }),
          initializeBranch({ name: "分支B" }),
        ];
    local.outputs = n.data.outputs
      ? JSON.parse(JSON.stringify(n.data.outputs))
      : [];
  },
  { immediate: true }
);
</script>

<style scoped>
.condition-config-panel {
  width: 480px;
  background: var(--color-bg-2, #fff);
  box-shadow: -2px 0 16px rgba(0, 0, 0, 0.08);
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 3002;
  padding: 24px 20px 16px 20px;
  display: flex;
  flex-direction: column;
  color: var(--color-text-1, #333);
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: var(--color-text-1, #374151);
}

.input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--color-border-2, #d1d5db);
  border-radius: 6px;
  font-size: 14px;
  margin-bottom: 6px;
  background: var(--color-bg-2, #fff);
  color: var(--color-text-1, #374151);
}

.input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.branches-list,
.outputs-list {
  margin-bottom: 12px;
}

.branch-item,
.output-item {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px;
  background: var(--color-fill-2, #f9fafb);
  border-radius: 6px;
}

.branch-name,
.output-name {
  flex: 1;
}

.branch-cond,
.output-type {
  flex: 2;
}

.del-btn {
  background: #ef4444;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.del-btn:hover {
  background: #dc2626;
}

.add-btn {
  background: var(--color-fill-2, #f3f4f6);
  color: #3b82f6;
  border: 1px solid var(--color-border-2, #d1d5db);
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  margin-top: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.add-btn:hover {
  background: var(--color-fill-3, #e5e7eb);
  border-color: var(--color-border-3, #9ca3af);
}

.panel-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: auto;
  padding-top: 16px;
  border-top: 1px solid var(--color-border-2, #e5e7eb);
}

.save-btn {
  background: #10b981;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 8px 18px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.save-btn:hover {
  background: #059669;
}

.close-btn {
  background: #6b7280;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 8px 18px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background: #4b5563;
}

/* Arco Design Vue 标签页样式覆盖 */
:deep(.arco-tabs-nav-tab) {
  background: var(--color-fill-2, #f9fafb);
  border-bottom: 1px solid var(--color-border-2, #e5e7eb);
}

:deep(.arco-tabs-nav-tab .arco-tabs-tab) {
  color: var(--color-text-3, #6b7280);
  font-weight: 500;
}

:deep(.arco-tabs-nav-tab .arco-tabs-tab-active) {
  color: #3b82f6;
  font-weight: 600;
}

:deep(.arco-tabs-content) {
  padding: 16px 0;
}

/* 分支层样式 */
.branches-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.branches-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--color-border-2, #e5e7eb);
}

.branches-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-1, #374151);
}

.branches-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.branch-container {
  border: 1px solid var(--color-border-2, #e5e7eb);
  border-radius: 8px;
  background: var(--color-bg-2, #fff);
  overflow: hidden;
}

.branch-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: var(--color-fill-2, #f9fafb);
  border-bottom: 1px solid var(--color-border-2, #e5e7eb);
}

.branch-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.branch-name-label {
  font-weight: 500;
  color: var(--color-text-1, #374151);
  font-size: 14px;
}

.branch-actions {
  display: flex;
  gap: 4px;
}

.branch-content {
  padding: 16px;
}

/* 条件规则构建器样式 */
.condition-builder {
  margin-top: 4px;
}

.mode-selector {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
  padding: 6px 8px;
  background: var(--color-fill-2, #f9fafb);
  border-radius: 4px;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.radio-item input[type="radio"] {
  width: 14px;
  height: 14px;
  accent-color: #3b82f6;
}

.radio-label {
  font-weight: 500;
  color: var(--color-text-1, #374151);
  font-size: 13px;
}

.rules-builder {
  border: 2px solid #3b82f6;
  border-radius: 6px;
  padding: 8px;
  background: var(--color-fill-1, #f8fafc);
}

.rules-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  padding-bottom: 6px;
  border-bottom: 1px solid var(--color-border-2, #e5e7eb);
}

.rules-title {
  font-weight: 500;
  color: var(--color-text-1, #374151);
  font-size: 13px;
}

.rules-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.rule-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px;
  background: var(--color-bg-2, #fff);
  border: 1px solid var(--color-border-2, #e5e7eb);
  border-radius: 3px;
}

.rule-actions {
  display: flex;
  gap: 2px;
}

/* 公式编辑器样式 */
.formula-editor {
  margin-top: 8px;
}

.formula-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.formula-label {
  font-weight: 500;
  color: var(--color-text-1, #374151);
  font-size: 13px;
}

.formula-input {
  width: 100%;
  min-height: 120px;
  resize: vertical;
}

/* Arco Design Vue 组件样式覆盖 - 移除强制颜色，让组件跟随主题 */
:deep(.arco-select-view) {
  color: var(--color-text-1, #374151) !important;
}

:deep(.arco-select-view .arco-select-view-value) {
  color: var(--color-text-1, #374151) !important;
}

:deep(.arco-input) {
  color: var(--color-text-1, #374151) !important;
}

:deep(.arco-input::placeholder) {
  color: var(--color-text-3, #9ca3af) !important;
}

:deep(.arco-btn) {
  color: var(--color-text-1, #374151) !important;
}

:deep(.arco-btn-text) {
  color: var(--color-text-1, #374151) !important;
}

:deep(.arco-btn-text:hover) {
  color: #3b82f6 !important;
  background-color: rgba(59, 130, 246, 0.1) !important;
}

:deep(.arco-textarea) {
  color: var(--color-text-1, #374151) !important;
}

:deep(.arco-textarea::placeholder) {
  color: var(--color-text-3, #9ca3af) !important;
}
</style>
